package com.studentportalen;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class LoginActivity extends Activity {
	
	DBHelper db;
	EditText _cid;
	EditText _pwd;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        db = Global.getDBHelper();
        _cid = (EditText)findViewById(R.id.edit_login_name);
        _pwd = (EditText)findViewById(R.id.edit_login_pwd);
           
    }
    
    /***
     * Logins user if correct user and pwd
     * @param view
     */
    public void login(View view){
    	Boolean loginCorrect = false;
    	String pwd = null;
    	int id = -1;
    	
    	try{
			String name = _cid.getText().toString();
			pwd = db.getStudentPasswordByName(name);
			id = db.getStudentIdByName(name);
    	}
    	catch(Exception ex){
    		String test = "";
    	}
    	
    	loginCorrect = (pwd != null && pwd.equals(_pwd.getText().toString()));
    	
    	if(loginCorrect){
    		//Set user as logged in in shared preferences
    		SharedPreferences sp = this.getSharedPreferences(Global.PREFS_NAME,MODE_PRIVATE);
    		SharedPreferences.Editor editor = sp.edit();
    		editor.putBoolean("loggedIn", true);
    		editor.putInt("studentId", id);
    		editor.commit();
    		
    		//Start home activity
	    	Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
	    	startActivity(intent);
    		finish();
    	}
    	else
    	{
    		//Tell user incorrect info by alert
    		AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
    		alertDialog.setTitle("Error");
    		alertDialog.setMessage("Wrong Username/Password.");
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int which) {
			     //here you can add functions
			  } });
			alertDialog.setCancelable(false);
			alertDialog.show();

    	}
    }
    
}
